/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.order.po.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.order.po.dao.model.PoHead;
import com.erp.order.po.dao.model.PoLine;
import com.erp.order.po.dao.model.PoLineBase;
import com.erp.order.po.dao.model.PoLineCO;
import com.erp.order.po.service.PoLineService;
import com.erp.order.poa.dao.model.PoAgreementLine;
import com.erp.order.poa.dao.model.PoAgreementLineCO;
import com.erp.order.poa.service.PoAgreementHeadService;
import com.erp.order.poa.service.PoAgreementLineService;
import com.erp.order.poeco.dao.model.PoLineM;
import com.erp.order.poeco.service.PoEcoService;
import com.erp.order.poeco.service.PoLineMService;

@Controller
@RequestMapping("/web/poLine")
public class PoLineWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(PoLineWebController.class);
    
    //服务层注入
    @Autowired
    private PoLineService poLineService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private PoLineMService poLineMService;
    @Autowired
    private PoAgreementHeadService poAgreementHeadService;
    @Autowired
    private PoAgreementLineService poAgreementLineService;
    @Autowired
    private PoEcoService poEcoService;
    
    
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getPoLineList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-07-15 15:57:23
     * @author 
     * @param pages
     * @param poLineCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getPoLineList")
    public String getPoLineList(Pages pages, PoLineCO poLineCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        pages.setMax(100);
        
        //分页查询数据
        List<PoLineBase> poLineList = new ArrayList<PoLineBase>();
        //根据version请求参数，判断数据从原表获取还是变更表获取
        if(poLineCO.getVersion()!=null&&poLineCO.getVersion()>0) {
            PoLineM poLineM = new PoLineM();
            poLineM.setPoHeadCode(poLineCO.getPoHeadCode());
            poLineM.setVersion(poLineCO.getVersion());
            List<PoLineM> list = this.poLineMService.getDataObjects(pages, poLineM);
            for(PoLineM obj: list) {
                poLineList.add(obj);
            }
        }else {
            List<PoLine> list = this.poLineService.getPoLineListByPoHeadCode(pages, poLineCO);
            for(PoLine obj: list) {
                poLineList.add(obj);
            }
        }
        
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //页面属性设置
        model.addAttribute("poLineList", poLineList);
        model.addAttribute("pages", pages);
        model.addAttribute("materialMap", materialMap);
        model.addAttribute("materialUnitMap", materialUnitMap);
        
        return "po/tab/poLineTab";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-07-15 15:57:23
     * @author 
     * @param poLine
     * @param model
     * @return String
     *
     */
    @RequestMapping("getPoLine")
    public String getPoLine(PoLine poLine, PoHead poHead, Model model) {
        //查询要编辑的数据
        Integer poLineIdSearch = 0;
        if(poLine!=null&&poLine.getPoLineId()!=null) {
            poLine = this.poLineService.getDataObject(poLine.getPoLineId());
            poLineIdSearch = poLine.getPoLineId();
        }else {
            poLine.setAmount(BigDecimal.ZERO);
        }
        
        //订单行的协议验证行
        Map<String, PoAgreementLine> poaLineMap = new HashMap<String, PoAgreementLine>();
        
        //如果是协议订单获取协议内容
        if(poHead!=null&&StringUtils.isNotBlank(poHead.getPoAgreementHeadCode())) {
            //获取协议头
            //PoAgreementHead poAgreementHead = this.poAgreementHeadService.getDataObject(poHead.getPoAgreementHeadCode());
            
            //获取协议行
            Pages pages = new Pages();
            pages.setPage(1);
            pages.setMax(100);
            PoAgreementLineCO poAgreementLineCO = new PoAgreementLineCO();
            poAgreementLineCO.setPoHeadCode(poHead.getPoAgreementHeadCode());
            List<PoAgreementLine> poAgreementLineList = this.poAgreementLineService.getPoLineListByPoHeadCode(pages, poAgreementLineCO);
            //设置订单行的协议验证行
            for(int a=0;a<poAgreementLineList.size();a++) {
                //获取协议已完成行数量,协议有数量限制才会计算发放数量
                /*if(poAgreementLineList.get(a).getQuantity()!=null) {
                    BigDecimal agreementFinishQuantity = this.poEcoService.getPoLineQuantityByAgreement(poAgreementLineList.get(a).getPoHeadCode(), poAgreementLineList.get(a).getMaterialCode(), poLineIdSearch);
                    poAgreementLineList.get(a).setAgreementFinishQuantity(agreementFinishQuantity);
                }
                
                //循环设置协议行map
                poaLineMap.put(poAgreementLineList.get(a).getMaterialCode(), poAgreementLineList.get(a));*/
            }
        }
        
        //物料
        Map<String, String> materialMap = this.masterDataCommonService.getMaterialMap();
        Map<String, String> materialLineMap = new HashMap<String, String>();
        //如果存在协议行则限定订单行的物料范围
        if(poaLineMap.size()>0) {
            for(String key: poaLineMap.keySet()) {
                materialLineMap.put(key, materialMap.get(key));
            }
        }else {
            materialLineMap.putAll(materialMap);
        }
        //去除订单行已存在的物料
        Pages pages = new Pages();
        pages.setPage(1);
        pages.setMax(100);
        PoLineCO poLineCO = new PoLineCO();
        poLineCO.setPoHeadCode(poLine.getPoHeadCode());
        //获取订单行
        List<PoLine> poLineList = this.poLineService.getPoLineListByPoHeadCode(pages, poLineCO);
        //循环删除已存在的物料
        for(PoLine poLineTemp: poLineList) {
            if(poLine!=null&&poLine.getPoLineId()!=null) {
                if(poLine.getPoLineId()!=poLineTemp.getPoLineId()) {
                    materialLineMap.remove(poLineTemp.getMaterialCode());
                }
            }else {
                materialLineMap.remove(poLineTemp.getMaterialCode());
            }
        }
        
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //页面属性设置
        model.addAttribute("poLine", poLine);
        model.addAttribute("materialMap", materialLineMap);
        model.addAttribute("materialUnitMap", materialUnitMap);
        model.addAttribute("poaLineMap", poaLineMap);
        
        return "po/pop/addLineModal";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-07-15 15:57:23
     * @author 
     * @param poLine
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editPoLine")
    @ResponseBody
    public String editPoLine(@Valid @RequestBody PoLine poLine, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        try {
            /*
            //参数校验
            Map<String, String> errorMap = this.validateParameters(bindingResult, model);
            if(errorMap.size()>0) {
                return "forward:getPoLine";
            }
            */
            
            //对当前编辑的对象初始化默认的字段
            if(poLine.getPoLineId()==null) {
                poLine.setPoLineCode(SnowFlake.getConcurrentId().toString());
            }
            
            //保存编辑的数据
            this.poLineService.insertOrUpdateDataObject(poLine);
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-07-15 15:57:23
     * @author 
     * @param poLine
     * @return String
     *
     */
    @RequestMapping("deletePoLine")
    @ResponseBody
    public String deletePoLine(@RequestBody PoLine poLine, RedirectAttributes attr) {
        try {
            //删除数据前验证数据
            if(poLine!=null&&poLine.getPoLineId()!=null) {
                //删除数据
                this.poLineService.deleteDataObject(poLine);
            }
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
}
